﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.BO;
using System.Data;
using System.IO;

namespace PPAP.Web.Master
{
    public partial class TemplateEdit : PageBase
    {
        public string FJID { set; get; }
        AttachmentTemplateBO bo = new AttachmentTemplateBO();
        AttachmentTypeBO tbo = new AttachmentTypeBO();
        LogBO lbo = new LogBO();
        T_FileBO manager = new T_FileBO();
        public string DID { set; get; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["DID"] != null)
                DID = Request.QueryString["DID"].ToString();
            if (!Page.IsPostBack)
            {
                for (int i = 1; i <= 60; i++)
                {
                    ddlSequence.Items.Add(new ListItem(GetSX(i), GetSX(i)));
                }
                if (Request.QueryString["DID"] != null)
                {
                    LoadDep(Request.QueryString["DID"].ToString());
                }
                else
                {
                    trTemplate.Visible = false;
                }

                
                //LoadData();
            }
            //if (Request.QueryString["deid"] != null)
            //{
            //    dele(Request.QueryString["deid"].ToString());
            //}
            if (Request.QueryString["deid"] != null)
            {
                DeleteFile(Request.QueryString["deid"].ToString());
            }
        }

        private string GetSX(int num)
        {
            if (num < 10)
                return "0" + num;
            else
                return num.ToString();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="fileid"></param>
        private void DeleteFile(string fileid)
        {
            try
            {
                DataSet ds = manager.Getpath(int.Parse(fileid));
                string path = ds.Tables[0].Rows[0]["F_Detail"].ToString();

                if (manager.DeleteFile(fileid))
                {
                    if(File.Exists(path)){
                    File.Delete(path);}
                    
                    //AlertReLoad("Deleted successful");
                    AlertRedirect("Deleted successful", "TemplateEdit.aspx?DID=" + Request.QueryString["DID"].ToString());
                    //AlertRedirect("Deleted successful", "Template.aspx");
                    //AlertBack("Deleted successful");
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        //private void dele(string id)
        //{
        //    int num = bo.Delete(int.Parse(id));
        //    lbo.WriteLog(CurrentUser.Name, "Delete Template");
        //    if (num > 0)
        //        AlertMessage("Deleted successful");
        //    LoadData();
        //}

        //private void LoadData()
        //{
        //    DataSet ds = bo.GetList();
        //    GridView1.DataSource = ds;
        //    GridView1.DataBind();
        //}

        private void LoadDep(string id)
        {
            Model.AttachmentTemplate d = bo.GetModel(int.Parse(id));
            Model.AttachmentType at = tbo.GetModel(int.Parse(id));
            if (at != null)
            {
                ddlIsEffective.SelectedValue = at.Xs.ToString();
                ddlSequence.SelectedValue = at.Sx.ToString();
            }
            txtAttachment.Text = d.Attachmenttype;
            txtRemark.Text = d.REMARK;
            ddlTemplateAccepted.SelectedValue = d.SUPPLIERSTEMPLATEACCEPTED.ToString();
            ddlTemplateAvailable.SelectedValue = d.BDNTTEMPLATEAVAILABLE.ToString();
            cbLevel1.Checked = d.ISLEVEL1 == 1 ? true : false;
            cbLevel2.Checked = d.ISLEVEL2 == 1 ? true : false;
            cbLevel3.Checked = d.ISLEVEL3 == 1 ? true : false;
            Button1.Visible = true;
            FJID = d.UPLOADEDFILE;
            //btnUp.Visible = true;
            lblUp.Text = "<input type='button'   class='button'  onclick='javascript:PopUpWindow(\"UploadFile.aspx?FJID=" + d.UPLOADEDFILE + "\", 230, 160, 730, 350);'   value='Upload'>";
            DataSet ds = manager.GetFileList(d.UPLOADEDFILE);
            if (ds.Tables[0].Rows.Count == 0)
            {
                DataRow dr = ds.Tables[0].NewRow();
                dr["F_Filename"] = "<font color='red'>No files available</font>";
                ds.Tables[0].Rows.Add(dr);
            }
            GridView2.DataSource = ds;
            GridView2.DataBind();
            Button1.Text = "Save";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["DID"] != null)
            {
                Model.AttachmentTemplate d = new Model.AttachmentTemplate();
                if (Request.QueryString["DID"] != null)
                    d = bo.GetModel(int.Parse(Request.QueryString["DID"].ToString()));
                int num = 0;
                d.REMARK = CheckWord(txtRemark.Text);
                d.SUPPLIERSTEMPLATEACCEPTED = int.Parse(ddlTemplateAccepted.SelectedValue);
                d.BDNTTEMPLATEAVAILABLE = int.Parse(ddlTemplateAvailable.SelectedValue);
                d.ISLEVEL1 = cbLevel1.Checked ? 1 : 0;
                d.ISLEVEL2 = cbLevel2.Checked ? 1 : 0;
                d.ISLEVEL3 = cbLevel3.Checked ? 1 : 0;
                d.LASTMODIFIEDDATE = DateTime.Now;
                //if (Button1.Text == "Add")
                //{
                //    num = bo.Add(d);
                //    lbo.WriteLog(CurrentUser.Id, "Add Template:" + d.Attachmenttype);
                //}
                //else
                //{
                d.ID = int.Parse(Request.QueryString["DID"].ToString());
                num = bo.Update(d);
                lbo.WriteLog(CurrentUser.Id, "Edit Template:" + d.Attachmenttype);
                //}
                //if (num > 0)
                //{
                //    txtAttachment.Text = "";
                //    txtRemark.Text = "";
                //    Button1.Text = "Add";
                //    Button1.Visible = false;
                //}

                Model.AttachmentType t = new Model.AttachmentType();
                t = tbo.GetModel(int.Parse(d.ID.ToString()));
                if (t != null)
                {
                    t.ATTACHMENTTYPE = CheckWord(txtAttachment.Text);
                    t.REMARK = CheckWord(txtRemark.Text);
                    t.CREATETIME = DateTime.Now;
                    t.CREATEDBY = CurrentUser.Id;
                    t.Sx = ddlSequence.SelectedValue;
                    t.Xs = int.Parse(ddlIsEffective.SelectedValue);
                    num = tbo.Update(t);
                }
                AlertReflashOpener("Save success");
            }
            else
            {
                Model.AttachmentType d = new Model.AttachmentType();
                int num = 0;
                if (txtAttachment.Text.Trim() == "")
                {
                    AlertMessage("Attachment Type is empty");
                    return;
                }
                d.ATTACHMENTTYPE = CheckWord(txtAttachment.Text);
                d.REMARK = CheckWord(txtRemark.Text);
                d.CREATETIME = DateTime.Now;
                d.CREATEDBY = CurrentUser.Id;
                d.Sx = ddlSequence.SelectedValue;
                d.Xs = int.Parse(ddlIsEffective.SelectedValue);
                num = tbo.Add(d);

                Model.AttachmentTemplate a = new Model.AttachmentTemplate();
                a.REMARK = CheckWord(txtRemark.Text);
                a.SUPPLIERSTEMPLATEACCEPTED = int.Parse(ddlTemplateAccepted.SelectedValue);
                a.BDNTTEMPLATEAVAILABLE = int.Parse(ddlTemplateAvailable.SelectedValue);
                a.ISLEVEL1 = cbLevel1.Checked ? 1 : 0;
                a.ISLEVEL2 = cbLevel2.Checked ? 1 : 0;
                a.ISLEVEL3 = cbLevel3.Checked ? 1 : 0;
                a.LASTMODIFIEDDATE = DateTime.Now;
                a.ATTACHMENTTYPEID = num;
                a.TEMPLATE = "";
                a.UPLOADEDBY = "";
                num = bo.Add(a);
                AlertReflashOpener("Add success");
            }
        }

        //添加操作
        private void DataInfo(string F_FileID, string F_Filename, string path, int type, string url, string filesize, string remarks, string upby)
        {
            manager.InsertFile(F_FileID, F_Filename, path, type, url, filesize, remarks, upby, "", "", "");
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Model.AttachmentTemplate d = bo.GetModel(int.Parse(Request.QueryString["DID"].ToString()));
            if (d != null)
            {
                FJID = d.UPLOADEDFILE;
                string FileName = file.FileName;
                if (!string.IsNullOrEmpty(FileName))
                {
                    string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
                    //if ((extension.ToLower() == ".pdf"))
                    //{
                        int fileSize = file.PostedFile.ContentLength;
                        if (fileSize == 0)
                        {
                            base.AlertMessage("The file does not exist！");
                        }
                        else
                        {
                            if (true)//限制大小为1M
                            {

                                string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string FileNam_Time = "";
                                int FileIndex = FileName.LastIndexOf("\\");
                                string FName = FileName.Substring(FileIndex + 1);
                                FileNam_Time =time+ FName;//日期和名称组合
                                string path = HttpContext.Current.Request.MapPath("../FileUpload/Template/" + FJID + "/");
                                string url = "../FileUpload/Template/" + FJID + "/" + time + FName;
                                DirectoryInfo upDir = new DirectoryInfo(path);
                                if (!upDir.Exists)
                                {
                                    upDir.Create();
                                }
                                file.SaveAs(path + FileNam_Time);
                                DataInfo(FJID, FName, path + time, 0, url, (fileSize / 1024.0).ToString("n") + "kb", "", CurrentUser.Id);
                                lbo.WriteLog(CurrentUser.Id, "Upload File:" + FName);
                               // AlertReflashOpener("Already upload");
                                //AlertRedirect("Already upload", "TemplateEdit.aspx?DID=" + Request.QueryString["DID"].ToString());
                                AlertMessage("Already upload");

                                Model.AttachmentTemplate t = bo.GetModel(int.Parse(Request.QueryString["DID"].ToString()));
                                FJID = d.UPLOADEDFILE;
                                //btnUp.Visible = true;
                                lblUp.Text = "<input type='button'   class='button'  onclick='javascript:PopUpWindow(\"UploadFile.aspx?FJID=" + d.UPLOADEDFILE + "\", 230, 160, 730, 350);'   value='Upload'>";
                                DataSet ds = manager.GetFileList(d.UPLOADEDFILE);
                                if (ds.Tables[0].Rows.Count == 0)
                                {
                                    DataRow dr = ds.Tables[0].NewRow();
                                    dr["F_Filename"] = "<font color='red'>No files available</font>";
                                    ds.Tables[0].Rows.Add(dr);
                                }
                                GridView2.DataSource = ds;
                                GridView2.DataBind();
                            }
                        }
                    //}
                    //else
                    //{
                    //    AlertMessage("Can't upload this file types,Please select a PDF file");
                    //}
                }
                else
                {
                    AlertMessage("Please select accessories！");
                }
            }
        }

    }
}